package com.common.libhttp.rxjava.observer;

import android.util.Log;

import com.common.libhttp.result.HttpResponseException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;

/**
 * <p>Description:
 * <p>
 * <p>Created by Devin Sun on 2017/3/29.
 */

public abstract class BaseObserver<T> implements Observer<T> {


    @Override
    public void onSubscribe(Disposable d) {
    }

    @Override
    public void onNext(T t) {
//        if (!Utils.isNetworkAvailable(App.getContext())){
//            Toast.makeText(App.getContext(),"当前网络不可用，请检查网络配置", Toast.LENGTH_SHORT).show();
//        }
        onSuccess(t);
    }

    @Override
    public void onError(Throwable e) {
//        if (!Utils.isNetworkAvailable(App.getContext())){
//            Toast.makeText(App.getContext(),"当前网络不可用，请检查网络配置", Toast.LENGTH_SHORT).show();
//        }
        Log.e("BaseObserver" , e.getLocalizedMessage());
        HttpResponseException responseException;
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            responseException = new HttpResponseException("网络请求出错", httpException.code());
        } else if (e instanceof HttpResponseException) {
            responseException = (HttpResponseException) e;
        } else {//其他或者没网会走这里
            responseException = new HttpResponseException("网络异常,请稍后重试", -1024);
        }

        onFailed(responseException);
    }

    @Override
    public void onComplete() {
    }

    protected abstract void onSuccess(T t);

    protected void onFailed(HttpResponseException responseException) {
//         Toast.makeText(responseException.getMessage() + "(" + responseException.getStatus() + ")").show();
        if (responseException.getStatus() == 100) {
//            Toast.makeText(Utils.getApp(),responseException.getMessage() + "(" + responseException.getStatus() + ")", Toast.LENGTH_SHORT).show();
//            ToastUitls.show(Utils.getApp(),responseException.getMessage() + "(" + responseException.getStatus() + ")");
//            AppDataManager.getInstance().setLogin(false);
//            Intent intent = new Intent(Utils.getApp(), LoginActivity.class);
//            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
//            ActivityLaunchUtils.startActivity(Utils.getApp(), intent);
        }
    }
}
